import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '../store'
import { userinfo } from '@/request/api'

Vue.use(VueRouter)

// 封装一个判断当前模块是否有权限
function hasUrl(url, next) {
  let result = store.getters.getUser.menus_url.some(item => url === item)
  if (result) {
    next()
  } else {
    next('/home')
  }

}

export const IndexRouters = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    beforeEnter(to, from, next) {
      hasUrl('/menu', next)
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    },
    beforeEnter(to, from, next) {
      hasUrl('/role', next)
    }
  },
  {
    path: '/user',
    component: () => import('../views/user/user.vue'),
    meta: {
      title: '管理员管理'
    },
    beforeEnter(to, from, next) {
      hasUrl('/user', next)
    }
  },
  {
    path: '/sort',
    component: () => import('../views/sort/sort.vue'),
    meta: {
      title: '商品分类'
    },
    beforeEnter(to, from, next) {
      hasUrl('/sort', next)
    }
  },
  {
    path:'/specs',
    component:()=>import('../views/goodsspecs/specs.vue'),
    meta:{
      title:'商品规格'
    },
    beforeEnter(to,from,next){
      hasUrl('/specs',next)
    }
  },
  {
    path:'/goods',
    component:()=>import('../views/goods/goods.vue'),
    meta:{
      title:'商品管理'
    },
    beforeEnter(to,from,next){
      hasUrl('/goods',next)
    }
  },
  {
    path:'/member',
    component:()=>import('../views/member/member.vue'),
    meta:{
      title:'会员管理'
    },
    beforeEnter(to,from,next){
      hasUrl('/member',next)
    }
  },
  {
    path:'/banner',
    component:()=>import('../views/banner/banner.vue'),
    meta:{
      title:'轮播图管理'
    },
    beforeEnter(to,from,next){
      hasUrl('/banner',next)
    }
  },
  {
    path:'/seck',
    component:()=>import('../views/seck/seck.vue'),
    meta:{
      title:'秒杀活动'
    },
    beforeEnter(to,from,next){
      hasUrl('/seck',next)
    }
  }
]

const routes = [
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue')
      },
      ...IndexRouters,
      {
        path: '',
        redirect: '/home'
      }
    ]
  },
  {
    path: '*',
    redirect: '/login'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 1、先检测用户进入的是否是登录页面
  if (to.path == '/login') {
    next()
    return;
  }
  // 2、判断用户是否登录
  if (store.getters.getUser) {
    next()
    return;
  }
  // 3、用户未登录跳转登录页
  next('/login')
})

export default router
